import createId from "@/lib/createId";
const localStorageKeyName = "tagList";
type Tag = {
  id: string;
  name: string;
};
type tagListModel = {
  data: Tag[];
  fetch: () => Tag[];
  add: (name: string) => "success" | "duplicated"; //string//success表示成功，duplicated表示name重复
  update: (id: string, name: string) => "success" | "NotFound" | "duplicated";
  remove:(id:string)=>boolean
  save: () => void;
};

const tagListModel: tagListModel = {
  data: [],
  fetch() {
    this.data = JSON.parse(
      window.localStorage.getItem(localStorageKeyName) || "[]"
    );
    return this.data;
  },
  add(name: string) {
    const names = this.data.map((item) => item.name);
    if (names.indexOf(name) >= 0) {
      return "duplicated";
    } else {   
      // 每次生成id
      const id = createId().toString()
      this.data.push({ id, name });
      this.save();
      return "success";
    }
  },
  update(id: string, name: string) {
    // 找到所有id
 
    const idList = this.data.map((item) => item.id);
    if (idList.indexOf(id) >= 0) {
      const nameList = this.data.map((item) => item.name);
      if (nameList.indexOf(name) >= 0) {
        return "duplicated";
      } else {
        const tag = this.data.filter((item) => item.id === id)[0];
        tag.id = tag.name = name;
        this.save();
        return "success";
      }
    } else {
      return "NotFound";
    }
  },
  remove(id:string){
    let index=-1
    for(let i = 0;i<this.data.length;i++){
        if(this.data[i].id ===id){
            index = i
            break
        }
    }
    this.data.splice(index,1)
    this.save()
    
    return true
  },
  save() {
    window.localStorage.setItem(localStorageKeyName, JSON.stringify(this.data));
  },
};
export default tagListModel;
